<?php

namespace backend\modules\admin\models;

use Yii;

class User extends \backend\models\User
{
    /**
     * Gets query for [[AuthItem]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getAuthItems()
    {
        return $this->getItemNames()->addOrderBy('type,name');
    }

    /**
     *  @brief 对用户授予指定权限项
     *  
     *  @param [in] type  授权项的类型，role 或 permission
     *  @param [in] items 授权项的名称数组
     *  @return 成功返回true，失败返回false
     */
    public function auth($type, $items){
        if(empty($items)) return false;
        $auth = Yii::$app->authManager;
        
        if($type=='permission'){
            $had = $auth->getPermissionsByUser($this->id);
            foreach($items as $item){
                if(array_key_exists($item, $had)){
                    $auth->assign($had[$item], $this->id);
                }
            }
        }elseif($type=='role'){
            $had = $auth->getRolesByUser($this->id);
            foreach($items as $item){
                if(array_key_exists($item, $had)){
                    $auth->assign($had[$item], $this->id);
                }
            }
        }
        
        return sizeof($items);
    }
    
    /**
     *  @brief 对用户撤销角色或权限的授权
     *  
     *  @param [in] items 授权项的名称数组
     *  @return 成功返回true，失败返回false
     */
    public function unAuth($items){
        if(empty($items)) return false;
        $deleted = AuthAssignment::deleteAll([
            'user_id' => $this->id,
            'item_name' => $items
        ]);
        return $deleted;
    }
}